﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Gfw.Infrastructure.Facilities;
using Gfw.Infrastructure.Stock.Enums;
using Gfw.Models.Stock;
using Gfw.Repositories.Stock;
using Gfw.Repository;

namespace Gfw.Infrastructure.Stock.Facilities
{
    public class MarketTrendFacility : IFacility
    {
        private decimal _price;
        private decimal _count;
        private DateTime _date;
        private TendencyTypeEnum _tendencyType;

        public MarketTrendFacility(TendencyTypeEnum tendencyType, decimal price, decimal count, DateTime date)
        {
            _date = date;
            _count = count;
            _price = price;
            _tendencyType = tendencyType;
        }

        public void Execute(Repository.UnitOfWork unitOfWork = null)
        {
            UnitOfWork work = unitOfWork ?? new UnitOfWork();

            TendencyRepository rep = new TendencyRepository();
            var tendency = rep.GetTendency(_date, (int) _tendencyType, work);
            if (tendency == null)
            {
                tendency = new StkTendency()
                               {
                                   Id = Guid.NewGuid().ToString(),
                                   TendencyDate = _date,
                                   TendencyPrice = _price,
                                   TendencyType = (int) _tendencyType,
                                   TendencyCount = _count
                               };
                rep.Save(tendency, work);
            }
            else
            {
                tendency.TendencyPrice = _price;
                tendency.TendencyCount = _count;
                rep.Update(tendency, work);
            }
            if (unitOfWork == null)
                work.Commit();
        }
    }
}
